#!/bin/bash
# Job yaml can send below ENVIRONMENT VARIABLES to me
# - mode
# - rtcwake	(dont show)
# - iterations
# - runtime	(dont show)
# - pm_test	(dont show)
# - idle_time	(dont show)
# - debug	(dont show)
# END ENVIRONMENT VARIABLES

. $LKP_SRC/lib/http.sh
. $LKP_SRC/lib/upload.sh
. $LKP_SRC/lib/job.sh
load_job_vars LKP_SERVER

[ -n "$mode" ] || mode='freeze'
[ -n "$iterations" ] || iterations=1
[ -n "$rtcwake" ] || rtcwake=60
[ -n "$idle_time" ] || idle_time=10

if [ -z "$runtime" ]
then
	runtime=$(( iterations * 120))
fi

rtcwake_file=/sys/class/rtc/rtc0/wakealarm

log_file=./log
dmesg_file=./dmesg.log
f_lkp_output=./suspend-stress

echo "SUSPEND RESUME TEST STARTED"

if [ "$mode" = "mem" ]
then
	if [ -f "/sys/power/mem_sleep" ]
	then
		chmod a+w /sys/power/mem_sleep
		echo deep > /sys/power/mem_sleep
		if [ $? -ne 0 ]
		then
			echo "mem sleep not supported. avaliable mem sleep type: $(cat /sys/power/mem_sleep)"
			exit 1
		fi
	fi
fi

if [ -n "$pm_test" ]
then
	echo "pm_test set to $pm_test"
	chmod a+w /sys/power/pm_test
	echo $pm_test > /sys/power/pm_test
	if [ $? -ne 0 ]
	then
		echo failed to set pm_test
		exit 1
	fi
	[ "none" = "$pm_test" ] && pm_test=""
fi

if [ "$mode" = "disk" ]
then
	echo "test_resume for hibernation is enabled"
	chmod a+w /sys/power/disk
	echo test_resume > /sys/power/disk
	if [ $? -ne 0 ]
	then
		echo failed to set test_resume
		exit 1
	fi
fi

for i in $(seq $iterations)
do
	echo "Suspend to $mode $i/$iterations:"
	echo "Suspend to $mode $i/$iterations:" >> $log_file

	retry=30
	while true
	do
		ping -c 1 -W 1 $LKP_SERVER > /dev/null
		[ $? -eq 0 ] && break
		echo network not ready
		echo network not ready >> $log_file
		retry=$((retry - 1))
		[ $retry -eq 0 ] && break
	done

	# restart network if network is not back in 10 seconds
	if [ $retry -eq 0 ]
	then
		$LKP_SRC/bin/run-ipconfig
		ping -c 1 -W 1 $LKP_SERVER > /dev/null
		if [ $? -ne 0 ]
		then
			echo network down
			echo network down >> $log_file
			[ -n "$debug" ] && sleep 72000
			exit 1
		fi
		echo network recovered by run-ipconfig
		echo network recovered by run-ipconfig >> $log_file
	fi

	if [ -n "$debug" ]
	then
		set_job_state "suspending_debug-$i/$iterations"
	else
		set_job_state "suspending-$i/$iterations"
	fi

	if [[ ( -z "$pm_test" ) && ( "$mode" != "disk" ) ]]
	then
		echo 0 > $rtcwake_file
		echo "+$rtcwake" > $rtcwake_file
		if [ $? -ne 0 ]
		then
			echo failed to set rtcwake
			ls /sys/class/
			ls /sys/class/rtc/
			ls -l /sys/class/rtc/rtc0/
			exit 1
		fi
	fi

	dmesg > $dmesg_file
	upload_files -t result $log_file
	upload_files -t result $dmesg_file
	#make sure test either PASS or FAIL, no INCOMPLETE
	echo "test started" > $f_lkp_output
	upload_files $f_lkp_output
	
	chmod a+w /sys/power/state
	echo $mode > /sys/power/state
	if [ $? -ne 0 ]
	then
		echo "Failed"
		exit 1
	fi
	echo "Done"
	echo "Done" >> $log_file
	echo "Sleep for $idle_time seconds"
	sleep $idle_time
done

rm $f_lkp_output
echo "SUSPEND RESUME TEST SUCCESS"
exit 0
